<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Model\ChSmartTagChangeLog;
use Mine\Abstracts\AbstractMapper;
use Mine\MineModel;
use function Hyperf\Collection\data_get;

class ChSmartTagChangeLogMapper extends AbstractMapper
{
    public function assignModel()
    {
        $this->model = ChSmartTagChangeLog::class;
    }

    public function getLogList(array $params): array
    {
        $contactId = data_get($params, 'contact_id');
        $tagGroupId = data_get($params, 'tag_group_id');
        $tagId = data_get($params, 'tag_id');
        $robotId = data_get($params, 'robot_id');
        $startTime = data_get($params, 'start_time');
        $endTime = data_get($params, 'end_time');


        $pageSize = (int)data_get($params, 'pageSize', MineModel::PAGE_SIZE);

        $data = $this->model::query()
            ->select(['id','contact_id','tag_id','robot_id','type','created_at'])
            ->with(['robot'=>function ($query) {
                $query->select(['id','nickname','avatar','corp_name']);
            },'contact'=>function ($query) {
                $query->select(['id','nickname','avatar','corp_short_name as corp_name','is_wechat']);
            },'tag'=>function ($query) {
                $query->select(['id','name']);
            }])
            ->when(!empty($contactId),function ($query) use ($contactId){
                $query->where('contact_id',$contactId);
            })
            ->when(!empty($robotId),function ($query) use ($robotId){
                $query->where('robot_id',$robotId);
            })
            ->when(!empty($tagGroupId),function ($query) use ($tagGroupId){
                $query->where('tag_group_id',$tagGroupId);
            })
            ->when(!empty($tagId),function ($query) use ($tagId){
                $query->where('tag_id',$tagId);
            })
            ->when(!empty($startTime) && !empty($endTime),function ($query) use ($startTime,$endTime){
                $query->whereBetween('created_at',[$startTime,$endTime]);
            })
            ->orderBy('created_at','desc')
            ->paginate($pageSize);

        $data->getCollection()->transform(function ($item){
           $item->type_text = $item->type == 0 ? '手动变更' : '自动变更';
           return $item;
        });

        return $this->setPaginate($data);
    }
}